package downloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class TextFileDownloader extends AbstractFileDownloader {

	public TextFileDownloader(String url) {
		super(url);
	}
	@Override
	public void download(){
		if(this.url == null){
			return;
		}
		FileWriter fw = null;
		BufferedReader reader = null;
		try {
			URL fileURL = new URL(this.url);
			URLConnection urlConnection = fileURL.openConnection();
			reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			File localFile = new File(this.getFileName());
			if(!localFile.exists()){
				if(!localFile.getParentFile().exists())
					localFile.getParentFile().mkdir();
				localFile.createNewFile();
			}
			fw = new FileWriter(localFile);
			String word = null;
			while((word = reader.readLine())!= null){
				fw.write(word);
				fw.write("\r\n");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(fw != null){
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
